package com.google.code.sysarch.v4.graphical;

import org.lwjgl.opengl.GL11;

public class Particle {

	public static final int MAX_PARTICLES = 1000;
	public static final float gravity = 1f;
	public static Particle[][] particles;
	public static Texture[] textures;
	public static int counter[];
	
	private float x, y, z;
	private float dx, dy, dz;
	private byte red, green, blue;
	
	Particle (int tex, float x, float y, float z, float dx, float dy, float dz) {
		this.x = x;
		this.y = y;
		this.z = z;
		this.dx = dx;
		this.dy = dy;
		this.dz = dz;
		while (particles[counter[tex]] != null) {
			counter[tex] = (counter[tex] + 1) % MAX_PARTICLES;
		}
		particles[tex][counter[tex]] = this;
	}
	
	public static void initParticles(Texture[] particles) {
		Particle.textures = particles;
		Particle.particles = new Particle[textures.length][MAX_PARTICLES];
		counter = new int[textures.length];
	}
	
	public void setColor(byte r, byte g, byte b) {
		this.red = r;
		this.green = g;
		this.blue = b;
	}
	
	public static void update(double delta) {
		for (int j=1; j<textures.length; j++) {
			for (int i=0; i<particles.length; i++) {
				if (particles[j][i] != null) {
					particles[j][i].x += particles[j][i].dx*delta;
					particles[j][i].y += particles[j][i].dy*delta;
					particles[j][i].z += particles[j][i].dz*delta;
					particles[j][i].dy -= gravity*delta;
					if (particles[j][i].y < 0) {
						particles[j][i] = null;
					}
				}
			}
		}
	}
	
	public static void render() {
		for (int j=1; j<textures.length; j++) {
			textures[j].bind();
			GL11.glBegin(GL11.GL_TRIANGLES);
			for (int i=0; i<particles.length; i++) {
				if (particles[j][i] != null) {
					GL11.glColor3b(particles[j][i].red, particles[j][i].green, particles[j][i].blue);
					GL11.glTexCoord2f(0, 0);
					GL11.glVertex3f(0, 0, 0); // Check this online at Nehe's
					// TODO Particle should always face the camera.
				}
			}
			GL11.glEnd();
		}
	}
	
	public static void explosion(float x, float y, float z, int density, float intensity) {
		for (int i=0; i<density; i++) {
			Particle p = new Particle(0, x, y, z, (float) (2*intensity*(Math.random()-.5)),
													(float) (intensity*Math.random()),
													(float) (2*intensity*(Math.random()-.5)));
			p.setColor((byte) 255, (byte)(255 - Math.random()*155), (byte) 0);
		}
	}
	
}
